package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"prod-manage/cache"
	"prod-manage/models"
	"strconv"
	"time"
)

func Create(c *gin.Context) {
	name := c.PostForm("name")
	num, _ := strconv.Atoi(c.PostForm("num"))
	class_id, _ := strconv.Atoi(c.PostForm("class_id"))

	if name == "" || num == 0 || class_id == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Product{
		Name:    name,
		Num:     num,
		ClassId: class_id,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	redis_key := "product_create_" + strconv.Itoa(int(data.ID))
	jsonData, _ := json.Marshal(&data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return

}

func Find(c *gin.Context) {
	var data []models.Product
	models.DB.Find(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查找成功",
		"data": data,
	})
	return
}
